import sys
import time
import threading
from PySide6.QtWidgets import QWidget, QGridLayout, QLabel, QPushButton, QLineEdit, QMessageBox, QComboBox, QApplication


class TimestampConversionWidget(QWidget):

    def __init__(self):
        super().__init__()
        self._enable_refresh_timestamp = True
        self._init()

    def _init(self):
        grid = QGridLayout()
        self.setLayout(grid)
        self.current_timestamp = QLabel(str(int(time.time())))
        self.timestamp = self._get_text_edit()
        self.format_date = self._get_text_edit()
        self.unit = QComboBox(self)
        self.unit.addItem('秒', 's')
        self.unit.addItem('毫秒', 'ms')
        self.format = self._get_text_edit('%Y-%m-%d %H:%M:%S')
        self.confirm = QPushButton("转换", self)

        x = 0
        grid.addWidget(QLabel('当前时间戳: ', self), x, 0, 1, 2)
        grid.addWidget(self.current_timestamp, x, 2, 1, 2)
        x += 1
        grid.addWidget(QLabel('时间戳: ', self), x, 0, 1, 2)
        grid.addWidget(self.timestamp, x, 2, 1, 2)
        x += 1
        grid.addWidget(QLabel('日期时间: ', self), x, 0, 1, 2)
        grid.addWidget(self.format_date, x, 2, 1, 2)
        x += 1
        grid.addWidget(QLabel('单位: ', self), x, 0)
        grid.addWidget(self.unit, x, 1)
        grid.addWidget(QLabel('格式化: ', self), x, 2)
        grid.addWidget(self.format, x, 3)
        x += 1
        grid.addWidget(self.confirm, x, 0, 1, 4)
        for i in range(x + 1):
            grid.setRowStretch(i, 1)

        self.confirm.clicked.connect(self._replace)
        threading.Thread(target=self._refresh_current_timestamp).start()

    def _replace(self):
        if self.timestamp.text():
            v = int(self.timestamp.text().strip())
            if self.unit.currentData() == 'ms':
                v /= 1000
            f = self.format.text().strip()
            try:
                self.format_date.setText(time.strftime(f, time.localtime(v)))
            except OSError:
                QMessageBox.question(self, "错误", "请检查单位是否一致", QMessageBox.StandardButton.Ok)
            except ValueError:
                QMessageBox.question(self, "错误", "请检查日期时间格式是否正确", QMessageBox.StandardButton.Ok)
        elif self.format_date.text():
            dt = self.format_date.text().strip()
            f = self.format.text().strip()
            v = int(time.mktime(time.strptime(dt, f)))
            if self.unit.currentData() == 'ms':
                v *= 1000
            self.timestamp.setText(str(v))
        else:
            QMessageBox.question(self, "错误", '时间戳和日期时间不能都为空', QMessageBox.StandardButton.Ok)

    def _get_text_edit(self, text=''):
        e = QLineEdit(text, self)
        e.resize(50, 20)
        return e

    def _refresh_current_timestamp(self):
        while self._enable_refresh_timestamp:
            now = time.time()
            if self.unit.currentData() == 'ms':
                now *= 1000
            self.current_timestamp.setText(str(int(now)))
            time.sleep(1)

    def close(self) -> bool:
        self._enable_refresh_timestamp = False
        s = super().close()
        return s


if __name__ == '__main__':
    app = QApplication()
    win = TimestampConversionWidget()
    win.show()
    sys.exit(app.exec())
